package com.ebraga.trackerclub.android.util.webservice;

import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * Provides methods to convert java objects to JSON string and opposite way. 
 */
public class JSONUtil {

	/**
	 * Deserializes a JSON string result into java Object.  
	 * @param jsonString a JSON string to be deserialized.
	 * @param clazz the deserialization target object.
	 * @return <code>clazz</code>.
	 */
	public static <T> T fromJSON(String jsonString, final Class<T> clazz) {
		final Gson gson = new GsonBuilder().create();
		return gson.fromJson(jsonString, clazz);
	}

	/**
	 * Deserializes generic types. 
	 * @param jsonString string to be deserialized.
	 * @param type generic type target of the deserialization.
	 * @return a generic type instance.
	 */
	public static Type fromJSON(String jsonString, Type type) {
		final Gson gson = new GsonBuilder().create();
		return gson.<Type>fromJson(jsonString, type);
	}
	
	/**
	 * Serializes a java object to JSON String.
	 * @param t object to be serialized.
	 * @return a JSON String representation of the given object.
	 */
	public static <T> String toJSON(final T t) {
		final Gson gson = new GsonBuilder().create();
		return gson.toJson(t);
	}
	
	/**
	 * Serializes a java object to JSON String.
	 * @param generic type to be serialized.
	 * @return a JSON String representation of the given object.
	 */
	public static String toJSON(Type type) {
		final Gson gson = new GsonBuilder().create();
		return gson.toJson(type);
	}

}
